package cn.zero.flowspringbootstater.configruation;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.redisson.RedissonClient;
import org.redisson.core.RLock;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * author: lei
 * <p>
 * date 2022/6/29 11:03
 **/
@Component
@Slf4j
public class IdFactory {

    @Resource
    private RedissonClient redissonClient;
    /**
     * 生成唯一id
     * 根据日期加随机数生成prex+17位数字的全局唯一编号
     * @param prex id前缀
     * @param lockName  所得名称
     * @return: java.lang.String
     * @author lei
     */

    public  String createCode(String prex,String lockName) {
        RLock lock = redissonClient.getLock(lockName);
        //阻塞等待1000毫秒 100毫秒后释放锁
        try {
            lock.tryLock(1000, 100, TimeUnit.MILLISECONDS);
            String code = prex + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss") + random(3, 100);
            return code;
        } catch (InterruptedException e) {
            log.error("生成模板id错误，错误原因：{}",e.getMessage());
            throw new RuntimeException("create id fail! msg:"+e.getMessage());
        } finally {
            //以防万一，手动释放一次 只释放当前线程的，防止将其他业务的锁释放掉
            if (lock.isLocked()&&lock.isHeldByCurrentThread())
            {
                lock.unlock();
            }
        }

    }


    /**
     * 生成一个 0-max 随机数字符串
     *
     * @param length: 字符串长度
     * @param max:    随机数最大值
     * @return: java.lang.String
     * @author: lei
     */

    public static String random(int length, int max) {
        double v = Math.floor(Math.random() * max);
        String s = String.valueOf(v);
        s = s.split("\\.")[0];
        StringBuilder builder = new StringBuilder(s);
        for (int i = 0; i < length - s.length(); i++) {
            builder.insert(0, "0");
        }
        return builder.toString();
    }
}
